import {
	login
} from "@/api/index.js"

const state = {
	openid: '',
	userInfo: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : {},
	token: '',
}

const actions = {
	loginAction({
		state,
		commit
	}) {
		return new Promise(resolve => {
			wx.login({
				success: (response) => {
					login({
						code: response.code
					}).then((res, err) => {
						console.log('wxLogin', res);
						if (res.body) {
							if(res.body.extraData) {
								uni.setStorageSync('messageList', JSON.stringify(res.body.extraData.messageList))
							}
							state.token = res.body.token
							uni.setStorageSync('token', state.token)
							state.userInfo.lasterLogTime = res.body.lastLogTime
							state.userInfo.uid = res.body.uid
							state.userInfo.avatarUrl = res.body.avatarUrl ? res.body.avatarUrl : '/static/image/defaultAvater.png'
							state.userInfo.nickName = res.body.nickName
							uni.setStorageSync('userInfo', JSON.stringify(state.userInfo))
							resolve()
						}
					})
				},
				fail(error) {
					console.error('wx.login failed:', error);
				}
			});
		})
	}
}

const mutations = {
	// 退出登录
	quit(state) {
		state.userInfo = {}
		uni.removeStorageSync('token')
		uni.removeStorageSync('userInfo')
	},
	// 存储token
	setToken(state, payload) {
		state.token = payload
		uni.setStorageSync('token', payload)
	},
	// 存储个人信息
	setUserInfo(state, payload) {
		state.userInfo = payload
		uni.setStorageSync('userInfo', JSON.stringify(payload))
		console.log('setStorageSync');
	}
}

const getters = {

}

export default {
	state,
	getters,
	actions,
	mutations
}